package com.lazy.example.simpledecoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by lazy on 7/12/16.
 */
@Sharable
public class ByteBufEchoHandler extends ChannelInboundHandlerAdapter {
    protected static final Logger logger = LoggerFactory.getLogger(ByteBufEchoHandler.class);


    public ByteBufEchoHandler(){
        logger.info("ByteBufEchoHandler@{}", this.hashCode());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("ByteBufEchoHandler@{},, {}@{}", this.hashCode(), ctx.getClass(), ctx.hashCode());
        if (msg instanceof ByteBuf) {
            logger.info("recv: {}", ByteBufUtil.hexDump((ByteBuf) msg));
            ctx.writeAndFlush(((ByteBuf) msg).copy());
        }

        // 数据交由用户简单处理就结束了
        ReferenceCountUtil.release(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception{
        super.channelActive(ctx);
        logger.info("channel active {}", ctx.channel().remoteAddress());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception{
        super.channelInactive(ctx);
        logger.info("channel Inactive {}", ctx.channel().remoteAddress());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
